<template>
	<view class="edit-reminder-container">
		<view class="form-container">
			<uni-forms ref="reminderForm" :model="formData" :rules="rules" label-position="top">
				<!-- 提醒类型 -->
				<uni-forms-item label="提醒类型" name="type">
					<view class="type-group">
						<view 
							class="type-item" 
							v-for="(item, index) in typeOptions" 
							:key="index"
							:class="{ active: formData.type === item.value }"
							@click="selectType(item.value)"
						>
							{{ item.label }}
						</view>
					</view>
				</uni-forms-item>
				
				<!-- 提醒标题 -->
				<uni-forms-item label="提醒标题" name="title">
					<uni-easyinput 
						v-model="formData.title" 
						placeholder="请输入提醒标题"
						:maxlength="20"
					/>
				</uni-forms-item>
				
				<!-- 提醒时间 -->
				<uni-forms-item label="提醒时间" name="time">
					<uni-datetime-picker 
						type="time" 
						format="HH:mm" 
						:clear-icon="false"
						v-model="formData.time" 
						@change="timeChange"
					/>
				</uni-forms-item>
				
				<!-- 重复规则 -->
				<uni-forms-item label="重复规则" name="repeat">
					<picker 
						:value="repeatIndex" 
						:range="repeatOptions" 
						range-key="label"
						@change="repeatChange"
					>
						<view class="uni-input">{{ repeatOptions[repeatIndex].label }}</view>
					</picker>
				</uni-forms-item>
				
				<!-- 重复星期选择 (仅周重复时显示) -->
				<uni-forms-item v-if="formData.repeat === 'weekly'" label="重复日期" name="repeatDays">
					<view class="week-group">
						<view 
							class="week-item" 
							v-for="(day, index) in weekdays" 
							:key="index"
							:class="{ active: formData.repeatDays.includes(index + 1) }"
							@click="toggleWeekday(index + 1)"
						>
							{{ day }}
						</view>
					</view>
				</uni-forms-item>
				
				<!-- 提醒描述 -->
				<uni-forms-item label="提醒描述" name="desc">
					<uni-easyinput 
						type="textarea" 
						v-model="formData.desc" 
						placeholder="请输入提醒描述（可选）"
						:maxlength="100"
					/>
				</uni-forms-item>
				
				<!-- 启用提醒 -->
				<uni-forms-item label="启用提醒" name="active">
					<switch :checked="formData.active" @change="activeChange" color="#8cc9a1" />
				</uni-forms-item>
			</uni-forms>
			
			<!-- 按钮组 -->
			<view class="btn-group">
				<button class="btn-cancel" @click="goBack">取消</button>
				<button class="btn-submit" @click="submitForm">保存</button>
			</view>
		</view>
	</view>
</template>

<script>
	import { getReminderDetail, updateReminder, initReminderData } from '@/common/api/reminder.js'
	
	export default {
		data() {
			return {
				reminderId: null,
				formData: {
					type: 'medicine',
					title: '',
					time: '08:00',
					repeat: 'daily',
					repeatDays: [1, 2, 3, 4, 5, 6, 7], // 1-7代表周一至周日
					desc: '',
					active: true
				},
				rules: {
					type: {
						rules: [{
							required: true,
							errorMessage: '请选择提醒类型'
						}]
					},
					title: {
						rules: [{
							required: true,
							errorMessage: '请输入提醒标题'
						}]
					},
					time: {
						rules: [{
							required: true,
							errorMessage: '请选择提醒时间'
						}]
					},
					repeat: {
						rules: [{
							required: true,
							errorMessage: '请选择重复规则'
						}]
					},
					repeatDays: {
						rules: [{
							validator: (rule, value, data, callback) => {
								// 如果是每周重复，则必须选择至少一天
								if (data.repeat === 'weekly' && (!value || value.length === 0)) {
									callback('请至少选择一天');
								}
								return true;
							}
						}]
					}
				},
				typeOptions: [
					{ label: '服药', value: 'medicine' },
					{ label: '血糖检测', value: 'bloodSugar' },
					{ label: '运动', value: 'exercise' },
					{ label: '饮食', value: 'diet' },
					{ label: '其他', value: 'other' }
				],
				repeatOptions: [
					{ label: '每天', value: 'daily' },
					{ label: '每周', value: 'weekly' },
					{ label: '仅一次', value: 'once' }
				],
				weekdays: ['周一', '周二', '周三', '周四', '周五', '周六', '周日']
			}
		},
		computed: {
			repeatIndex() {
				return this.repeatOptions.findIndex(item => item.value === this.formData.repeat)
			},
			
			// 获取重复规则文本
			repeatText() {
				if (this.formData.repeat === 'daily') {
					return '每天';
				} else if (this.formData.repeat === 'once') {
					return '仅一次';
				} else if (this.formData.repeat === 'weekly') {
					// 格式化选择的星期
					if (this.formData.repeatDays.length === 7) {
						return '每天'; // 如果选择了所有天，则显示为每天
					} else {
						const dayNames = this.formData.repeatDays.map(day => this.weekdays[day - 1]);
						return '每周' + dayNames.join('、');
					}
				}
				return '';
			}
		},
		onLoad(options) {
			// 确保本地数据已初始化
			initReminderData()
			
			if (options.id) {
				this.reminderId = options.id
				this.loadReminderDetail()
			} else {
				uni.showToast({
					title: '提醒ID不存在',
					icon: 'none'
				})
				setTimeout(() => {
					uni.navigateBack()
				}, 1500)
			}
		},
		methods: {
			// 加载提醒详情
			async loadReminderDetail() {
				uni.showLoading({
					title: '加载中...'
				})
				
				try {
					// 从本地存储获取详情
					const res = await getReminderDetail(this.reminderId)
					
					if (res.code === 0 && res.data) {
						const reminder = res.data
						
						// 更新表单数据
						this.formData = {
							type: reminder.type,
							title: reminder.title,
							time: reminder.time,
							repeat: reminder.repeat,
							repeatDays: [...reminder.repeatDays], // 复制数组
							desc: reminder.desc || '',
							active: reminder.active
						}
					} else {
						throw new Error(res.message || '提醒不存在')
					}
				} catch (e) {
					console.error('获取提醒详情失败:', e)
					uni.showToast({
						title: '获取提醒详情失败',
						icon: 'none'
					})
					
					setTimeout(() => {
						uni.navigateBack()
					}, 1500)
				} finally {
					uni.hideLoading()
				}
			},
			
			// 选择类型
			selectType(type) {
				this.formData.type = type
			},
			
			// 时间变更
			timeChange(e) {
				this.formData.time = e
			},
			
			// 重复规则变更
			repeatChange(e) {
				const index = e.detail.value
				const value = this.repeatOptions[index].value
				this.formData.repeat = value
				
				// 如果选择了每周，但没有选择任何日期，默认选择工作日
				if (value === 'weekly' && (!this.formData.repeatDays || this.formData.repeatDays.length === 0)) {
					this.formData.repeatDays = [1, 2, 3, 4, 5] // 默认工作日
				}
			},
			
			// 切换星期选择
			toggleWeekday(day) {
				const index = this.formData.repeatDays.indexOf(day)
				if (index === -1) {
					// 添加
					this.formData.repeatDays.push(day)
				} else {
					// 移除
					this.formData.repeatDays.splice(index, 1)
				}
			},
			
			// 开关状态变更
			activeChange(e) {
				this.formData.active = e.detail.value
			},
			
			// 返回上一页
			goBack() {
				uni.navigateBack()
			},
			
			// 提交表单
			async submitForm() {
				this.$refs.reminderForm.validate().then(async (res) => {
					uni.showLoading({
						title: '保存中...'
					})
					
					try {
						// 构建更新数据
						const reminder = {
							...this.formData
						}
						
						// 设置重复规则文本
						reminder.repeatText = this.repeatText
						
						// 更新提醒
						const res = await updateReminder(this.reminderId, reminder)
						if (res.code === 0) {
							// 提示成功
							uni.showToast({
								title: '更新成功',
								icon: 'success'
							})
							
							// 返回上一页
							setTimeout(() => {
								uni.navigateBack()
							}, 1500)
						} else {
							throw new Error(res.message || '更新失败')
						}
					} catch (e) {
						console.error('更新提醒失败:', e)
						uni.showToast({
							title: typeof e === 'string' ? e : '更新失败',
							icon: 'none'
						})
					} finally {
						uni.hideLoading()
					}
				}).catch(err => {
					console.log('表单验证失败:', err)
				})
			}
		}
	}
</script>

<style lang="scss">
	.edit-reminder-container {
		padding: 30rpx;
		background-color: #f5f7fa;
		min-height: 100vh;
	}
	
	.form-container {
		background-color: #fff;
		border-radius: 16rpx;
		padding: 40rpx 30rpx;
		box-shadow: 0 8rpx 24rpx rgba(0, 0, 0, 0.08);
	}
	
	/* 类型选择组 */
	.type-group {
		display: flex;
		flex-wrap: wrap;
		margin: 0 -10rpx 20rpx;
		
		.type-item {
			padding: 16rpx 30rpx;
			background-color: #f5f7fa;
			border-radius: 12rpx;
			margin: 10rpx;
			font-size: 28rpx;
			color: #666;
			transition: all 0.3s ease;
			border: 1px solid #f0f0f0;
			
			&.active {
				background: linear-gradient(135deg, #8cc9a1 0%, #5daa7f 100%);
				color: #fff;
				box-shadow: 0 8rpx 16rpx rgba(140, 201, 161, 0.3);
				transform: translateY(-2rpx);
				border-color: transparent;
			}
		}
	}
	
	/* 星期选择器 */
	.week-group {
		display: flex;
		flex-wrap: wrap;
		margin: 0 -10rpx 20rpx;
		
		.week-item {
			width: 80rpx;
			height: 80rpx;
			display: flex;
			align-items: center;
			justify-content: center;
			background-color: #f5f7fa;
			border-radius: 50%;
			margin: 10rpx;
			font-size: 28rpx;
			color: #666;
			transition: all 0.3s ease;
			border: 1px solid #f0f0f0;
			
			&.active {
				background: linear-gradient(135deg, #8cc9a1 0%, #5daa7f 100%);
				color: #fff;
				box-shadow: 0 8rpx 16rpx rgba(140, 201, 161, 0.3);
				transform: translateY(-2rpx);
				border-color: transparent;
			}
		}
	}
	
	/* 选择器样式 */
	.uni-input {
		height: 80rpx;
		padding: 0 20rpx;
		background-color: #f9f9f9;
		border: 1px solid #f0f0f0;
		border-radius: 12rpx;
		display: flex;
		align-items: center;
		font-size: 28rpx;
		color: #333;
	}
	
	/* 按钮组 */
	.btn-group {
		display: flex;
		margin-top: 60rpx;
		padding: 0 20rpx;
		
		button {
			flex: 1;
			height: 100rpx;
			display: flex;
			align-items: center;
			justify-content: center;
			border-radius: 50rpx;
			font-size: 32rpx;
			transition: all 0.3s ease;
			border: none;
		}
		
		.btn-cancel {
			background-color: #f9f9f9;
			color: #666;
			margin-right: 30rpx;
			box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.05);
			
			&:active {
				background-color: #f0f0f0;
				transform: translateY(2rpx);
			}
		}
		
		.btn-submit {
			background: linear-gradient(135deg, #8cc9a1 0%, #5daa7f 100%);
			color: #fff;
			box-shadow: 0 8rpx 20rpx rgba(140, 201, 161, 0.3);
			
			&:active {
				transform: translateY(4rpx);
				box-shadow: 0 4rpx 8rpx rgba(140, 201, 161, 0.3);
			}
		}
	}
</style> 